package com.card.auth;

import org.apache.commons.codec.digest.DigestUtils;

import com.card.redis.JedisService;
import com.card.util.SpringUtil;

/**
 * ClassName: JWTUtil <br/>
 * Function: token. <br/>
 * date: 2018年10月16日 下午12:09:43 <br/>
 * 
 * @author lishuai11
 * @version
 * @since JDK 1.8
 */
public class TokenUtil {

	private final static String SECRET_KEY = "credit:";// 私钥

	private final static int TOKEN_EXP = 60 * 60 * 24 * 30;// 过期时间

	public static String getToken(int userId) throws Exception {
		String key = redisUser(userId);
		String token = DigestUtils.md5Hex(key + System.currentTimeMillis());
		JedisService jedisService = SpringUtil.getBean("jedisService");
		jedisService.setex(token, TOKEN_EXP, key);
		return token;
	}

	public static boolean tokenIsExpire(String token) throws Exception {
		JedisService jedisService = SpringUtil.getBean("jedisService");
		if (jedisService.isExist(token)) {
			return false;
		} else {
			return true;
		}
	}

	public static boolean tokenIsValid(int userId, String token) throws Exception {
		JedisService jedisService = SpringUtil.getBean("jedisService");
		String user = jedisService.get(token);
		if (user != null && !user.equals("") && user.equals(redisUser(userId))) {
			return true;
		}
		return false;
	}

	public static void delToken(String token) throws Exception {
		JedisService jedisService = SpringUtil.getBean("jedisService");
		if (jedisService.isExist(token)) {
			jedisService.delete(token);
		}
	}

	private static String redisUser(int userId) {
		return SECRET_KEY + userId;
	}

}
